package com.wyp.controller;

import com.wyp.common.Result;
import com.wyp.entity.User;
import com.wyp.service.GoodsService;
import com.wyp.service.UserService;
import com.wyp.utils.redis.RedisService;
import com.wyp.utils.redis.prekey.pre.GoodsKey;
import com.wyp.vo.GoodsDetailVO;
import com.wyp.vo.GoodsVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author: Oliver
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {
    private static Logger log = LoggerFactory.getLogger(GoodsController.class);
    @Autowired
    UserService userService;
    @Autowired
    RedisService redisService;
    @Autowired
    GoodsService goodsService;
    @Autowired
    ThymeleafViewResolver thymeleafViewResolver;

    /**
     * 跳转到登录页面
     * 页面级别的缓存实现，首先查询缓存 --不存在查数据库--放缓存  --显示  查出来时候需要先进行手动解析换成html页面在进行缓存操作
     * 测试结果：
     * 样例 500*10
     * QPS 1700
     *
     * @return
     */
    @RequestMapping(value = "to_list", produces = "text/html")
    @ResponseBody
    public String toGoodsList(HttpServletRequest request, HttpServletResponse response, Model model, User user) {
        //log.info(user.getNickname());
        List<GoodsVO> goodsVoList = goodsService.getGoodsVoList();
        model.addAttribute("goodsList", goodsVoList);
        //取缓存
        String html = redisService.get(GoodsKey.GOODS_KEY, "", String.class);
        if (!StringUtils.isEmpty(html)) {
            return html;
        }
        WebContext webContext = new WebContext(request, response,
                request.getServletContext(), request.getLocale(), model.asMap());

        //手动渲染html页面进行返回
        html = thymeleafViewResolver.getTemplateEngine().process("goods_list", webContext);
        if (!StringUtils.isEmpty(html)) {
            redisService.set(GoodsKey.GOODS_KEY, "", html);
        }
        return html;
    }


    /**
     * 获取商品详情
     * 页面静态化 html+ajax
     *
     * @param model
     * @param user
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/to_detail/{goodsId}")
    @ResponseBody
    public Result<GoodsDetailVO> goodsDetail(Model model, User user, @PathVariable("goodsId") Long goodsId) {
        GoodsVO goods = goodsService.getGoodsVOById(goodsId);

        //秒杀状态MSStatus
        //秒杀剩余时间
        long endDate = goods.getEndDate().getTime();
        long startDate = goods.getStartDate().getTime();
        long now = System.currentTimeMillis();
        int MSStatus = 0;
        int remainSeconds = 0;
        if (now < startDate) {//还没有开始，计算倒计时时间
            MSStatus = 0;
            remainSeconds = (int) (startDate - now) / 1000;
        } else if (now > endDate) {
            //已经结束
            MSStatus = 2;
            remainSeconds = -1;
        } else {
            //进行中
            MSStatus = 1;
            remainSeconds = 0;
        }
        GoodsDetailVO vo = new GoodsDetailVO();
        vo.setGoods(goods);
        vo.setUser(user);
        vo.setRemainSeconds(remainSeconds);
        vo.setMSStatus(MSStatus);
        return Result.success(vo);
    }

    /**
     * 获取商品详情
     * 使用url级别缓存，也就是对某一个请求对象进行缓存。
     * 方法：先从缓存中取--没有就去查-手动渲染页面-然后放缓存
     *
     * @param model
     * @param user
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/to_detail2/{goodsId}", produces = "text/html")
    @ResponseBody
    public String goodsDetail2(HttpServletRequest request, HttpServletResponse response, Model model, User user, @PathVariable("goodsId") Long goodsId) {
        //取缓存
        String html = redisService.get(GoodsKey.GOODS_KEY_ID, "" + goodsId, String.class);
        if (!StringUtils.isEmpty(html)) {
            return html;
        }
        GoodsVO goods = goodsService.getGoodsVOById(goodsId);
        model.addAttribute("goods", goods);
        model.addAttribute("user", user);

        //秒杀状态MSStatus
        //秒杀剩余时间
        long endDate = goods.getEndDate().getTime();
        long startDate = goods.getStartDate().getTime();
        long now = System.currentTimeMillis();
        int MSStatus = 0;
        int remainSeconds = 0;
        if (now < startDate) {//还没有开始，计算倒计时时间
            MSStatus = 0;
            remainSeconds = (int) (startDate - now) / 1000;
        } else if (now > endDate) {
            //已经结束
            MSStatus = 2;
            remainSeconds = -1;
        } else {
            //进行中
            MSStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("MSStatus", MSStatus);
        model.addAttribute("remainSeconds", remainSeconds);
        WebContext webContext = new WebContext(request, response,
                request.getServletContext(), request.getLocale(), model.asMap());

        //手动渲染html页面进行返回
        html = thymeleafViewResolver.getTemplateEngine().process("goods_detail", webContext);
        if (!StringUtils.isEmpty(html)) {
            redisService.set(GoodsKey.GOODS_KEY_ID, "" + goodsId, html);
        }
        return html;
    }

}
